package com.inspsys.common.utils.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONObject;
import com.inspsys.common.constant.Constants;
import com.inspsys.common.utils.StringUtils;

/**
 * 通用http发送方法
 * 
 * @author inspsys
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url 发送请求的 URL
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url) {
        return sendGet(url, StringUtils.EMPTY);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        return sendGet(url, param, Constants.UTF8);
    }

    /**
     * 向指定 URL 发送GET方法的请求
     *
     * @param url         发送请求的 URL
     * @param param       请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @param contentType 编码类型
     * @return 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param, String contentType) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            String urlNameString = StringUtils.isNotBlank(param) ? url + "?" + param : url;
            log.info("sendGet - {}", urlNameString);
            URL realUrl = new URL(urlNameString);
            URLConnection connection = realUrl.openConnection();
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), contentType));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendGet ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendGet SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendGet IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendGet Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url   发送请求的 URL
     * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            log.info("sendPost - {}", url);
            URL realUrl = new URL(url);
            URLConnection conn = realUrl.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            log.info("recv - {}", result);
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param,
                    e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
            }
        }
        return result.toString();
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    // public static String sendPost(String url, Map<String, String> params, String
    // body) {
    // PrintWriter out = null;
    // BufferedReader in = null;
    // StringBuilder result = new StringBuilder();
    // JSONObject json = new JSONObject();
    // JSONObject request = new JSONObject();

    // try {
    // // 拼接 param 参数到 URL
    // if (!Objects.isNull(params) && params.size() > 0) {
    // String paramString = getKeyAndValueStr(params);
    // url += "?" + paramString;
    // }

    // request.put("url", url);
    // request.put("body", body);
    // json.put("request", request);

    // log.info("sendPost - {}", url);
    // URL realUrl = new URL(url);
    // URLConnection conn = realUrl.openConnection();
    // conn.setConnectTimeout(5000); // 连接超时时间5秒
    // conn.setReadTimeout(10000); // 读取数据的超时时间10秒
    // conn.setRequestProperty("accept", "*/*");
    // conn.setRequestProperty("connection", "Keep-Alive");
    // conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64;
    // x64)");
    // conn.setRequestProperty("Accept-Charset", "utf-8");
    // conn.setRequestProperty("contentType", "utf-8");
    // conn.setDoOutput(true);
    // conn.setDoInput(true);

    // out = new PrintWriter(conn.getOutputStream());
    // out.print(body);
    // out.flush();
    // in = new BufferedReader(new InputStreamReader(conn.getInputStream(),
    // StandardCharsets.UTF_8));
    // String line;
    // while ((line = in.readLine()) != null) {
    // result.append(line);
    // }
    // log.info("recv - {}", result);
    // return result.toString();
    // } catch (ConnectException e) {
    // result.append(e.getMessage());
    // log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" +
    // params, "body=" + body, e);
    // } catch (SocketTimeoutException e) {
    // result.append(e.getMessage());
    // log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url +
    // ",param=" + params, "body=" + body,
    // e);
    // } catch (IOException e) {
    // result.append(e.getMessage());
    // log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" +
    // params, "body=" + body, e);
    // } catch (Exception e) {
    // result.append(e.getMessage());
    // log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + params,
    // "body=" + body, e);
    // } finally {
    // try {
    // if (out != null) {
    // out.close();
    // }
    // if (in != null) {
    // in.close();
    // }
    // } catch (IOException ex) {
    // result.append(ex.getMessage());
    // log.error("调用in.close Exception, url=" + url + ",param=" + params, "body=" +
    // body, ex);
    // }
    // }
    // // return result.toString();

    // json.put("response", result.toString());
    // json.put("isOk", "0");
    // return json.toString();
    // }

    public static String sendPost(String url, Map<String, String> params, String body, Map<String, String> headers) {
        HttpURLConnection connection = null;
        OutputStream os = null;
        BufferedReader reader = null;
        String result = "{}";
        JSONObject json = new JSONObject();
        JSONObject request = new JSONObject();

        try {
            // 拼接 param 参数到 URL
            String paramString = getParamsString(params);
            if (!paramString.isEmpty()) {
                url += "?" + paramString;
            }

            request.put("url", url);
            request.put("body", body);
            json.put("request", request);

            // 创建连接
            URL requestUrl = new URL(url);
            connection = (HttpURLConnection) requestUrl.openConnection();
            connection.setConnectTimeout(10000); // 连接超时时间5秒
            connection.setReadTimeout(20000); // 读取数据的超时时间10秒
            // 设置请求方法和头部
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 写入 body 到请求体
            if (body != null && !body.isEmpty()) {
                os = connection.getOutputStream();
                os.write(body.getBytes("UTF-8"));
                os.flush();
            }
            // 读取响应
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                result = response.toString();
                json.put("response", result);
                json.put("isOk", "1");
                return json.toString();
            } else {
                result = "请求失败，未获取到数据";
                log.error("请求失败, url=" + url + ",param=" + params, "body=" + body, "状态码：" + responseCode);
            }
        } catch (Exception e) {
            result = e.getMessage();
            log.error("调用Exception, url=" + url + ",param=" + params, "body=" + body, e);
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                result = e.getMessage();
                log.error("调用IOException, url=" + url + ",param=" + params, "body=" + body, e);
                e.printStackTrace();
            }
        }
        json.put("response", result);
        json.put("isOk", "0");
        return json.toString();
    }

    public static String sendSSLPost(String url, String param) {
        StringBuilder result = new StringBuilder();
        String urlNameString = url + "?" + param;
        try {
            log.info("sendSSLPost - {}", urlNameString);
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            URL console = new URL(urlNameString);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
            conn.setRequestProperty("Accept-Charset", "utf-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !"".equals(ret.trim())) {
                    result.append(new String(ret.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
                }
            }
            log.info("recv - {}", result);
            conn.disconnect();
            br.close();
        } catch (ConnectException e) {
            log.error("调用HttpUtils.sendSSLPost ConnectException, url=" + url + ",param=" + param, e);
        } catch (SocketTimeoutException e) {
            log.error("调用HttpUtils.sendSSLPost SocketTimeoutException, url=" + url + ",param=" + param, e);
        } catch (IOException e) {
            log.error("调用HttpUtils.sendSSLPost IOException, url=" + url + ",param=" + param, e);
        } catch (Exception e) {
            log.error("调用HttpsUtil.sendSSLPost Exception, url=" + url + ",param=" + param, e);
        }
        return result.toString();
    }

    private static class TrustAnyTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * 获得k1=v1&k2=v2 字符串(排序)
     * 
     * @param map
     * @return
     */
    public static String getKeyAndValueStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, Comparator.comparing(Map.Entry::getKey));
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null || item.getKey() != "") {
                    String key = item.getKey();
                    String val = item.getValue();
                    if (!(val == "" || val == null)) {
                        sb.append(key + "=" + val + "&");
                    }
                }
            }
            result = sb.toString().substring(0, sb.length() - 1);
        } catch (Exception e) {
            return null;
        }
        return result;
    }

    /**
     * 将 Map 参数转换为查询字符串
     * 
     * @param params
     * @return
     */

    private static String getParamsString(Map<String, String> params) throws Exception {
        if (params == null || params.isEmpty()) {
            return "";
        }
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
                    .append("&");
        }
        result.setLength(result.length() - 1); // 删除末尾的 &
        return result.toString();
    }

}